package com.atiffarrukh.get.inspired;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.facebook.FacebookActivity;
import com.facebook.GraphUser;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.SessionState;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class FacebookLogIn extends FacebookActivity {
	private static final String APP_ID = "110978142397253";
	private Facebook fb;
	String postQuote;
	Context context;
	private Handler mRunOnUi = new Handler();
	private String notConnected = "You are not connected to any Network"; 
	
	private static final String TAG = "FacebookLogIn";
	
	@Override
	  public void onCreate(Bundle savedInstanceState) {
	      super.onCreate(savedInstanceState);
	      //setContentView(R.layout.activity_main);
	      Log.d(TAG, "onCreate()");
	      if(isConnected()){
	    	  	this.openSession();
	      		fb = new Facebook(APP_ID);
	      
	      		Bundle b = getIntent().getExtras();
	      		postQuote = b.getString("postValue");
	      		Log.d(TAG, "Session must open now.");
	      }else{
	        	Toast.makeText(getApplicationContext(), notConnected, Toast.LENGTH_LONG).show();
	        	Intent i = new Intent(this, MainActivity.class);
	        	startActivity(i);
	      }
	          
	  }
	


		private boolean isConnected() {
				// TODO Auto-generated method stub
				boolean isConntected = true;
				NetworkInfo activeNetwork;
		        ConnectivityManager cm;
		        Log.d(TAG, "isConnected()");
		        try{
		        cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
		        activeNetwork = cm.getActiveNetworkInfo();
		        isConntected = activeNetwork.isConnected();
		        }catch(RuntimeException e){
		        	isConntected = false;
		        	Toast.makeText(this,notConnected, Toast.LENGTH_LONG).show();
		        	return isConntected;
		        }
		        
		        Log.d(TAG, "Value of isConnected == " + isConntected);
		        return isConntected;
		        
			}


	@Override
	  protected void onSessionStateChange(SessionState state, Exception exception) {
	    // user has either logged in or not ...
	    if (state.isOpened()) {
	    // make request to the /me API
	      Request request = Request.newMeRequest(this.getSession(), new Request.GraphUserCallback() {
	        // callback after Graph API response with user object
	        @SuppressWarnings("deprecation")
			@Override
	        public void onCompleted(GraphUser user, Response response) {
	          if (user != null) {
	        	  Log.d("tag", "THis is LOG");
	        	  
	        	  //AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(fb);
	        	  
	              Bundle params = new Bundle();
	              Log.d("Quote", postQuote);
	              params.putString("message", postQuote);
	              params.putString("name", "Get Inspired");
	              params.putString("caption", postQuote);
	              params.putString("link", "https://play.google.com/store/apps/details?id=com.atiffarrukh.get.inspired");
	              params.putString("description", " ");
	              params.putString("picture", "http://i46.tinypic.com/23scftl.jpg");
	       
	              //mAsyncFbRunner.request(null, params, "POST", new WallPostListener(), null);
	              
	              fb.dialog(FacebookLogIn.this, "stream_publish", params, new WallPostListener());
	              //mAsyncFbRunner.request("feed", params, "POST", new WallPostListener(), null);
	              
	          }
	          Log.d("Session", "CLOSED");
	        }
	      });
	      Request.executeBatchAsync(request);
	      //finish();
	    }
	  }
	  
	  
	  private final class WallPostListener implements DialogListener {
	        public void onComplete(final String response, Object state) {
	            mRunOnUi.post(new Runnable() {
	                @Override
	                public void run() {
	                    	 
	                    //Toast.makeText(FacebookLogIn.this,"Posted to Facebook", Toast.LENGTH_SHORT).show();
	                }
	            });
	        }

			@Override
			public void onComplete(Bundle values) {
				// TODO Auto-generated method stub
				//Toast.makeText(context, R.string.facebookPost, Toast.LENGTH_SHORT).show();
				goBack();
			}

			@Override
			public void onFacebookError(FacebookError e) {
				// TODO Auto-generated method stub
				//finish();
			}

			@Override
			public void onError(DialogError e) {
				// TODO Auto-generated method stub
				//finish();
			}

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				finish();
				goBackCancel();
			}

		}
		private void goBackCancel() {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "Your post has been canceled", Toast.LENGTH_LONG).show();
			/*Intent i = new Intent(this,MainActivity.class);
			startActivity(i);*/
			finish();
		}
	  void goBack(){
		  	//Toast.makeText(getApplicationContext(), "Your post has been posted", Toast.LENGTH_LONG).show();
			/*Intent i = new Intent(this,MainActivity.class);
			startActivity(i);*/
			finish();
	  }
	  
	  /*@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Intent i = new Intent(this,MainActivity.class);
		startActivity(i);
	  }*/
	  @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//finish();
	  }
}
